"""
-------------------------------
- File_Name: lifespan.py
- Date: 2025/2/19
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 生命周期
-------------------------------
"""
from fastapi import FastAPI
from contextlib import asynccontextmanager, AsyncExitStack
from app.logging.config import log
from app.models import Api
from app.core.init_app import modify_db,init_menus,init_data
from app.dependencies.transactionDepend import db_pools
from config import get_api_environment_var

api_environment = get_api_environment_var()

"""生命周期
项目启动前刷新api列表,非orm数据库连接池

"""
from fastapi.routing import APIRoute

async def refresh_api_list():
    from main import app
    existing_apis = [(str(api.method.value), api.path) for api in await Api.all()]
    app_routes = [route for route in app.routes if isinstance(route, APIRoute)]
    app_routes_compared = [(list(route.methods)[0].lower(), route.path_format) for route in app_routes]
    for method, path in set(existing_apis) - set(app_routes_compared):
        await Api.filter(method=method, path=path).delete()

    for route in app_routes:
        method = list(route.methods)[0].lower()
        path = route.path_format
        summary = route.summary
        tags = list(route.tags)
        await Api.update_or_create(path=path, method=method, defaults=dict(summary=summary, tags=tags))


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 初始化App log
    log.info(f"Application程序开始...")
    # 初始化
    async with AsyncExitStack() as stack:
        await stack.enter_async_context(db_pools())
        await modify_db()
        await init_menus()
        await init_data()
        # 刷新api列表
        log.info(f"刷新api接口列表")
        await refresh_api_list()
        yield
    log.info(f"Application程序结束...")